<template>
  <div class="other-income-expense">
    <!-- 筛选区 -->
    <el-form :model="filter" inline class="filter-bar">
      <!-- 单据日期 -->
      <el-form-item label="单据日期">
        <el-date-picker
          v-model="filter.dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          :default-value="[new Date('2025-06-01'), new Date('2025-06-26')]"
        />
      </el-form-item>

      <!-- 业务员选择（弹窗） -->
      <el-form-item label="业务员">
        <el-button type="primary" @click="openDialog('salesman')">
          {{ selectedSalesman.name || "请选择业务员" }}
        </el-button>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注">
        <el-input
          v-model="filter.remark"
          placeholder="请输入备注查询"
          clearable
        />
      </el-form-item>

      <!-- 客户类别（树形下拉） -->
      <el-form-item label="客户类别">
        <el-cascader
          v-model="filter.customerCategory"
          :options="customerCategoryTree"
          :props="{ label: 'label', value: 'id', children: 'children' }"
          placeholder="类别"
          clearable
        />
      </el-form-item>

      <!-- 所有类别（下拉） -->
      <el-form-item label="所有类别">
        <el-select v-model="filter.incomeType" placeholder="所有类别" clearable>
          <el-option label="所有类别" value="all" />
          <el-option label="其它收入" value="income" />
          <el-option label="其它支出" value="expense" />
        </el-select>
      </el-form-item>

      <!-- 查询按钮 -->
      <el-form-item>
        <el-button type="primary" @click="queryData">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- ========== 业务员选择弹窗 ========== -->
    <el-dialog
      title="选择业务员"
      v-model="dialogs.salesman.visible"
      width="600px"
    >
      <div class="dialog-header">
        <el-input
          v-model="dialogs.salesman.keyword"
          placeholder="请输入职员编号或名称"
          clearable
          style="width: 240px"
        />
        <el-checkbox v-model="dialogs.salesman.showDisabled" class="ml-4"
          >显示禁用职员</el-checkbox
        >
        <el-button type="primary" class="ml-4" @click="fetchSalesmen"
          >查询</el-button
        >
      </div>

      <el-table
        :data="dialogs.salesman.list"
        :row-key="(row) => row.id"
        @selection-change="handleSalesmanSelect"
        border
        style="width: 100%; margin-top: 8px"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column
          prop="code"
          label="职员编号"
          min-width="120"
          sortable
        />
        <el-table-column
          prop="name"
          label="职员名称"
          min-width="180"
          sortable
        />
      </el-table>

      <el-pagination
        @size-change="(val) => (dialogs.salesman.limit = val)"
        @current-change="(val) => (dialogs.salesman.page = val)"
        :current-page="dialogs.salesman.page"
        :page-sizes="[10, 20, 50]"
        :page-size="dialogs.salesman.limit"
        :total="dialogs.salesman.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 12px"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.salesman.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmSalesmanSelection"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- ========== 收支明细表 ========== -->
    <!-- 空状态 -->
    <div class="empty-state" v-if="tableData.length === 0">
      <i class="el-icon-document" style="font-size: 48px; color: #dcdcdc"></i>
      <p>暂无内容，点击查询试试吧</p>
    </div>

    <!-- 表格（有数据时显示） -->
    <el-table
      v-else
      :data="tableData"
      border
      show-summary
      :summary-method="generateSummary"
      :header-cell-style="{ background: '#F8F9FA' }"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="date" label="日期" min-width="120" sortable />
      <el-table-column
        prop="billNo"
        label="单据编号"
        min-width="120"
        sortable
      />
      <el-table-column prop="salesman" label="业务员" min-width="120" />
      <el-table-column prop="type" label="收支类别" min-width="100" />
      <el-table-column prop="item" label="收支项目" min-width="120" />
      <el-table-column
        prop="income"
        label="收入"
        align="right"
        min-width="120"
      />
      <el-table-column
        prop="expense"
        label="支出"
        align="right"
        min-width="120"
      />
      <el-table-column prop="partner" label="往来单位" min-width="120" />
      <el-table-column prop="remark" label="摘要" min-width="180" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";

// ========== 筛选条件 ==========
const filter = reactive({
  dateRange: [new Date("2025-06-01"), new Date("2025-06-26")],
  salesman: null, // 选中的业务员对象
  remark: "", // 备注
  customerCategory: [], // 客户类别树形选中值（数组，如 [2, 22] 对应华北地区→批发）
  incomeType: "all", // 所有类别：all/income/expense
});

// ========== 选中业务员回显 ==========
const selectedSalesman = ref({ name: "" });

// ========== 对话框状态 ==========
const dialogs = reactive({
  salesman: {
    visible: false,
    keyword: "", // 搜索关键词
    showDisabled: false, // 显示禁用职员
    list: [], // 职员列表
    page: 1, // 分页页码
    limit: 10, // 分页大小
    total: 0, // 总条数
    selected: [], // 选中的职员（多选，实际业务通常单选）
  },
});

// ========== 基础数据模拟 ==========
// 客户类别树形数据
const customerCategoryTree = ref([
  {
    id: 1,
    label: "广东省内",
    children: [],
  },
  {
    id: 2,
    label: "华北地区",
    children: [
      { id: 21, label: "零售" },
      { id: 22, label: "批发" },
    ],
  },
  {
    id: 3,
    label: "华东地区",
    children: [{ id: 31, label: "批发" }],
  },
  {
    id: 4,
    label: "华南地区",
    children: [],
  },
  {
    id: 5,
    label: "华中地区",
    children: [],
  },
]);

// 模拟职员列表（与界面数据一致）
const mockSalesmen = [
  { id: 1, code: "D0001", name: "老板", disabled: false },
  { id: 2, code: "D0002", name: "财务-玲", disabled: false },
  { id: 3, code: "D0003", name: "采购-小陈", disabled: true },
  { id: 4, code: "D0004", name: "采购-小王", disabled: false },
  { id: 5, code: "D0005", name: "销售-小李", disabled: false },
  { id: 6, code: "D0006", name: "销售-小东", disabled: false },
  { id: 7, code: "D0007", name: "旗舰店店员", disabled: false },
  { id: 8, code: "D0008", name: "2店店员", disabled: false },
  { id: 9, code: "D0009", name: "1号仓库管员", disabled: false },
];

// 模拟收支明细数据
const mockRecords = [
  {
    date: "2025-06-01",
    billNo: "B0001",
    salesman: "销售-小李",
    type: "收入",
    item: "服务费",
    income: 5000.0,
    expense: 0,
    partner: "XX公司",
    remark: "服务费收入",
    customerCategory: "华北地区-批发", // 关联客户类别
  },
  {
    date: "2025-06-05",
    billNo: "B0002",
    salesman: "采购-小王",
    type: "支出",
    item: "办公费",
    income: 0,
    expense: 1200.0,
    partner: "XX供应商",
    remark: "购买办公用品",
    customerCategory: "广东省内",
  },
  {
    date: "2025-06-10",
    billNo: "B0003",
    salesman: "老板",
    type: "收入",
    item: "租金收入",
    income: 8000.0,
    expense: 0,
    partner: "YY公司",
    remark: "六月租金",
    customerCategory: "华东地区-批发",
  },
  {
    date: "2025-06-15",
    billNo: "B0004",
    salesman: "财务-玲",
    type: "支出",
    item: "水电费",
    income: 0,
    expense: 500.0,
    partner: "电力公司",
    remark: "上月水电费",
    customerCategory: "华中地区",
  },
];

// ========== 对话框交互逻辑 ==========
/** 打开业务员选择弹窗 */
const openDialog = (type) => {
  if (type === "salesman") {
    dialogs.salesman.visible = true;
    fetchSalesmen(); // 初始化加载职员
  }
};

/** 获取职员列表（筛选+分页） */
const fetchSalesmen = () => {
  const { keyword, showDisabled, page, limit } = dialogs.salesman;

  let filtered = mockSalesmen.filter((item) => {
    // 搜索筛选
    if (keyword) {
      return item.code.includes(keyword) || item.name.includes(keyword);
    }
    return true;
  });

  // 禁用筛选
  if (!showDisabled) {
    filtered = filtered.filter((item) => !item.disabled);
  }

  // 分页处理
  const start = (page - 1) * limit;
  const end = start + limit;
  dialogs.salesman.list = filtered.slice(start, end);
  dialogs.salesman.total = filtered.length;
};

/** 职员表格多选事件 */
const handleSalesmanSelect = (val) => {
  dialogs.salesman.selected = val;
};

/** 确认选择业务员（单选处理） */
const confirmSalesmanSelection = () => {
  if (dialogs.salesman.selected.length === 0) {
    ElMessage.warning("请选择业务员");
    return;
  }
  // 业务场景通常为单选，取第一个选中项
  const salesman = dialogs.salesman.selected[0];
  selectedSalesman.value = { name: salesman.name };
  filter.salesman = salesman; // 保存选中的业务员
  dialogs.salesman.visible = false;
  ElMessage.success("业务员选择成功！");
};

// ========== 数据查询逻辑 ==========
const tableData = ref([]);

/** 查询收支明细 */
const queryData = () => {
  console.log("执行查询", filter); // 添加日志，便于调试

  // 1. 基础过滤（日期、业务员、备注）
  let filtered = mockRecords.filter((record) => {
    // 日期范围
    const recordDate = new Date(record.date);
    if (recordDate < filter.dateRange[0] || recordDate > filter.dateRange[1]) {
      return false;
    }

    // 业务员
    if (filter.salesman && record.salesman !== filter.salesman.name) {
      return false;
    }

    // 备注
    if (filter.remark && !record.remark.includes(filter.remark)) {
      return false;
    }

    return true;
  });

  // 2. 客户类别过滤（树形选中）
  if (filter.customerCategory.length > 0) {
    // 获取所有选中的类别标签（含子节点）
    const selectedLabels = getSelectedCategoryLabels(
      filter.customerCategory.map((id) =>
        findNodeById(customerCategoryTree.value, id)
      )
    );
    filtered = filtered.filter((record) =>
      selectedLabels.includes(record.customerCategory)
    );
  }

  // 3. 所有类别过滤（收入/支出）
  if (filter.incomeType === "income") {
    filtered = filtered.filter((record) => record.type === "收入");
  } else if (filter.incomeType === "expense") {
    filtered = filtered.filter((record) => record.type === "支出");
  }

  tableData.value = filtered;

  // 添加成功提示
  ElMessage.success(`查询成功，共找到 ${filtered.length} 条记录`);
};

/** 递归查找树形节点（根据ID） */
function findNodeById(nodes, id) {
  for (const node of nodes) {
    if (node.id === id) return node;
    if (node.children) {
      const childNode = findNodeById(node.children, id);
      if (childNode) return childNode;
    }
  }
  return null;
}

/** 递归获取所有选中节点的标签（含子节点） */
function getSelectedCategoryLabels(nodes) {
  const labels = [];
  function traverse(node) {
    labels.push(node.label);
    if (node.children && node.children.length) {
      node.children.forEach(traverse);
    }
  }
  nodes.forEach(traverse);
  return labels;
}

/** 合计行计算（收入、支出总和） */
const generateSummary = ({ columns, data }) => {
  const sums = [];
  let totalIncome = 0;
  let totalExpense = 0;

  data.forEach((item) => {
    totalIncome += item.income;
    totalExpense += item.expense;
  });

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计:";
      return;
    }
    if (column.prop === "income") {
      sums[index] = totalIncome.toFixed(2);
    } else if (column.prop === "expense") {
      sums[index] = totalExpense.toFixed(2);
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

// ========== 初始化 ==========
onMounted(() => {
  tableData.value = []; // 初始无数据
});
</script>

<style scoped>
.other-income-expense {
  padding: 24px;
  background: #fff;
}

.filter-bar {
  margin-bottom: 16px;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 0;
  color: #999;
}

/* 合计行样式 */
.el-table__footer-row td {
  background-color: #fff2cc !important;
  font-weight: 500;
}

/* 表头样式 */
.el-table th {
  text-align: center;
}
</style>